package com.yunhai.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static String encryptMD5(String input) {
        try {
            // 获取MD5 MessageDigest 实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 使用指定的字节更新摘要
            md.update(input.getBytes());

            // 完成哈希计算，得到结果
            byte[] digest = md.digest();

            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e); // 如果MD5算法不存在，抛出运行时异常
        }
    }

    public static void main(String[] args) {
        String originalString = "hello world";
        String encryptedString = encryptMD5(originalString);
        System.out.println("Original: " + originalString);
        System.out.println("Encrypted (MD5): " + encryptedString);
    }
}